import router from "../index.ts";
import { getToken } from "@/utils/auth.ts";
import { filterRoutes } from "@/utils/route.ts";
import useRouterStore from "@/stores/router.ts";

import router_config from "@/router/router_config.ts";

let hasAddedAsyncRoutes = true; // 标记是否已添加异步路由

const title = import.meta.env.VITE_GLOB_APP_TITLE;
const titleSeparator = import.meta.env.VITE_GLOB_APP_TITLE_SEPARATOR;
const token = import.meta.env.VITE_GLOB_TOKEN_KEY;

// 全局路由守卫
router.beforeEach(async (to, _, next) => {
  let hasToken = getToken(token);
  if (hasToken) {
    if (to.path === "/login") {
      next({ path: router_config.defaultRoute, replace: true });
    } else {
      const hasRoutes = filterRoutes(useRouterStore().setRoutes());
      if (hasAddedAsyncRoutes) {
        for (const route of hasRoutes) {
          router.addRoute(route);
        }
        hasAddedAsyncRoutes = false;
        next({ ...to, replace: true });
      } else {
        next();
      }
    }
    console.log(router.getRoutes(), "getRoutes");
  } else {
    if (router_config.routesWhiteList.includes(to.path)) {
      next();
    } else {
      next({ path: "/login", query: { redirect: to.path }, replace: true });
    }
  }
});

router.afterEach((to, _) => {
  if (to.meta.title) {
    document.title = `${to.meta.title}${titleSeparator}${title}`;
  } else {
    document.title = title;
  }
});
